<?php
/**
 * 站外文章控制器
 */
namespace Home\Controller;
use Think\Controller;
class ArticleController extends InitController {


   //抓取文章
	public function file_put(){
		$article_id =  I('article_id');
		$task_url = I('task_url');
		$article_type_task = I('article_type_task',0,intval);
		
		//判断会员等级和使用天数(暂时不需要加上商家id)
		/* $judge_member =  judge_member_probation($this->opt,$this->info);
		if($this->info['level'] == '0' && !$judge_member){
			header("Content-Type: text/html; charset=UTF-8");
			echo '<script>alert("非会员不能使用");window.history.go(-1)</script>';
			exit();
		} */

		if(empty($article_id)){
			$this->error("服务器繁忙",U('Index/Index'));
		}

		$article_type = "1";
		$cwhere = array('id'=>$article_id);
		$ContentLog = M('ContentLog')->where($cwhere)->field('content,article_source')->find();
		$contents = htmlspecialchars_decode($ContentLog['content']);
		$article_source = $ContentLog['article_source'];

		//过滤样式cursor:default 否则会有某些设置了cursor：defalut的样是不能使用编辑器
		if(!empty($contents)) {
			$contents = str_replace('cursor: default;', '', $contents);
		}

		$this->assign(array(
			'contents'=>$contents,
			'article_source'=>$article_source,	//判断什么类型的网站处理，返回页面js需要处理一些事情
			'article_type'=>$article_type,//文章类型0站内，1获取
			'url'=>$task_url,
			'article_type_task'=>$article_type_task,
		));
	   	$this->display('article_edit');
	}

	//抓取微信图片，下载本地(由于使用的是微信图片名字，所以不会出现重复图片)
	public function file_picture(){
		$image = new \Org\Net\Http;
        //模拟header头
        $url  = I('url');
        $type = I('type','jpg');
        if(empty($url)){
            return $url;
        }
        $header = wx_header();
		//获取图片名
        $position       = strpos($url,'mmbiz/');
        $picture_u      = substr($url,$position+6);
        $position_slash = strripos($picture_u,'/');
        $picture_name   = substr($picture_u,0,$position_slash);
        if(empty($type) || $type == 'undefined'){
			$type = 'jpg';
		}
		
        $img_array      = get_article_img($url,$picture_name,$type);
        /*
		########以前抓取图片的代码，暂时保留
		$upload       = C('upload_path').'/';//上传路径
        $ryear          = date('Y',NOW_TIME);
		$rmonth         = date('m',NOW_TIME);
		$rdate          = date('d',NOW_TIME);
		//文件夹
		$upload_path    = $upload.'temporary/'.$ryear.'/'.$rmonth.'/'.$rdate;
		//创建文件夹
		mkDirs($upload_path);
		$picture = $upload_path.'/'.$picture_name.'.'.$type;

		//下载图片
		$result = $image->curlDownload($url,$picture,$header);*/

		//组装md5_file散列数组(保存图片)
		$md5_file = md5_file("./".$img_array[0]."");
		if(!empty($md5_file)){
			$result = M('HomePictureAttachment')->where(' `key` = "'.$md5_file.'" ')->find();
		}
		if(empty($result)){
			$date = array(
				'img_name'=>$picture_name,
				'upload_time'=>NOW_TIME,
				'picture_address'=>$img_array[0],
				'key'=>$md5_file,
				'user_id'=>$this->uid,
				'is_article'=>1,
				'type'=>$type
			);
			D('Article')->picture_attachments($date);
		}

		//返回下载图片
 	    $this->ajaxReturn(array('status'=>'1','msg'=>'/'.$img_array[0]));
	}


	//获取模板组件信息
	public function gain_item_info(){
		if(!IS_AJAX){
			return false;
		}
		$tid    = I('id',0,'intval');
		$result = D('Ad')->select_ad($this->uid,$tid);
		if(!$result){
			$this->ajaxReturn(array('status'=>'-1','msg'=>'网路原因，插入失败'));
		}else{
			$this->ajaxReturn(array('status'=>'1','msg'=>'成功','data'=>$result));
		}
	}

	//提交文章内容
	function article_submit(){
		if(!IS_AJAX){
			return false;
		}
		$article_id = I('aid',0,'intval'); //文章id
		$music_id = I('music_id',0,'intval'); //音乐music_id
		$title      = I('title','','trim');//标题不能为空
		$type       = I('type','0'); //文章类型
		$share_introduction       = I('share_introduction','','trim'); //分享简介
		$upload       = I('upload','','trim'); //上传图片
		$article_type_task = I('article_type_task', 0,'intval'); //普通文章，任务文章

		if(empty($title)){
			$this->ajaxReturn(array('status'=>'-1','msg'=>'标题不能为空'));
		}
		
		$content = file_get_contents("php://input"); //文章内容(这种方法获取，不会被框架过滤)
		//文章内容替换(替换链接等)
		if(!empty($content)){
			$content = replace_content($content);
		}
		
		if(empty($article_id)){
			$search = array(
		        '@<script[^>]*?>.*?</script>@si',  // Strip out javascript
			);
			$content = preg_replace($search, '', $content);
			
			//判断参数
			$data = array(
				'uid'=>$this->uid,
				'title'=>$title,
				'content'=>$content,
				'type'=>$type,
				'createtime'=>NOW_TIME,
				'music_id'=>$music_id,
				'share_summary'=>$share_introduction,
				'share_img'=>$upload,
                'article_type'=>$article_type_task,
			);

			
			//判断文章审核是否开启，0：不开启，1：开启
			if($this->opt['article_review'] == '0'){
				$data['status'] = 1;
			}

			$judge = D('Article')->insert_article($data);
			if($judge){

				//判断文章审核是否开启，0：不开启，1：开启
				if($this->opt['article_review'] == '0'){
					$jumpurl = I('jumpurl') ? I('jumpurl') : U('Home/Publish/article_detail');
					$jumpurl.="?aid=".$judge;
					$this->ajaxReturn(array('status'=>'1','msg'=>'文章保存成功','url'=>$jumpurl,'open'=>'0'));
				}else{
					$this->ajaxReturn(array('status'=>'1','msg'=>'文章保存成功,审核中','url'=>U('Home/Article/article_list'),'open'=>'1'));
				}

			}else{
				$this->ajaxReturn(array('status'=>'-1','msg'=>'网路原因，文章保存失败'));
			}
		}else{

			$seo_key = I('seo_key','','trim');
			$seo_depict = I('seo_depict','','trim');
			if(empty($article_id)){
				$this->ajaxReturn(array('status'=>'-1','msg'=>'网路原因，更新失败'));
			}
			
			//判断当前会员是文章会员，如果是就更新，不是就插入
			$detail_info =  D('Article')->article_detail($article_id,1);

			//用户站内文章
			if($detail_info['uid'] != $this->uid){
				$data = array(
					'uid'=>$this->uid,
					'title'=>$title,
					'content'=>$content,
					'type'=>$type,
					'seo_depict'=>$seo_depict,
					'seo_key'=>$seo_key,
					'createtime'=>NOW_TIME,
					'music_id'=>$music_id,
					'share_summary'=>$share_introduction,
					'share_img'=>$upload,
				);

				//判断文章审核是否开启，0：不开启，1：开启
				if($this->opt['article_review'] == '0'){
					$data['status'] = 1;
				}

				$judge = D('Article')->insert_article($data);

				if($judge !== false){

					//判断文章审核是否开启，0：不开启，1：开启
					if($this->opt['article_review'] == '0'){
						$jumpurl = I('jumpurl') ? I('jumpurl') : U('Home/Publish/article_detail');
						$jumpurl.="?aid=".$judge;
						$this->ajaxReturn(array('status'=>'1','msg'=>'文章保存成功','url'=>$jumpurl,'open'=>'0'));
					}else{
						$this->ajaxReturn(array('status'=>'1','msg'=>'文章保存成功,审核中','url'=>U('Home/Article/article_list')));
					}

				}else{
					$this->ajaxReturn(array('status'=>'-1','msg'=>'网路原因，文章更新失败'));
				}
			}else{
				//更新文章
				$data = array(
					'uid'=>$this->uid,
					'title'=>trim($title),
					'content'=>trim($content),
					'status'=>1,
					'music_id'=>$music_id,
					'share_summary'=>$share_introduction,
					'share_img'=>$upload,
				);
				$judge = D('Article')->update_detail($this->uid,$article_id,$data);

				if($judge !== false){
					$jumpurl = I('jumpurl') ? I('jumpurl') : U('Home/Publish/article_detail');
					$jumpurl.="?aid=".$article_id;
					$this->ajaxReturn(array('status'=>'1','msg'=>'文章保存成功','url'=>$jumpurl,'open'=>'0'));
				}else{
					$this->ajaxReturn(array('status'=>'-1','msg'=>'网路原因，文章更新失败'));
				}
			}
		}
	}

	//加载文章列表
	public function article_list(){
		$page         = I('page',0,'intval');
		$limit        = '';
		$index        = 10;
		$page_all     = 0;
		$files        = 'id,title,createtime';
		//获取页数
		if(!empty($page)){
			$now_page = ($page + 1);
			$page_all = $page * $index;
			$limit    = $page_all.','.$index;
		}else{
			$limit    = '0,10';
		}

		 $article_list = D('Article')->article_list($this->uid,$limit,$files);
		 //文章阅读数
		 if(!empty($article_list)){
			foreach($article_list as $k=>$v){
				$sql = "select count(na.id) as num from `ng_article` as na inner join `ng_article_flow` as naf on na.id = naf.aid where na.id = {$v['id']}";
				$num = M()->query($sql);
				$article_list[$k]['read'] = $num[0]['num'];
			}

		 }

		 //用于ajax分页
		 if(IS_AJAX){

			if(!empty($article_list)){
				foreach($article_list as $k=>$v){
					$article_list[$k]['createtime'] = date('Y年m月d日 H:i:s',$v['createtime']);
					$article_list[$k]['url'] = U('Home/Publish/article_detail',array('aid'=>$article_list[$k]['id']),true,true);
				}

				$status = 1;
			}else{
				$status = -1;
			}
			return $this->ajaxReturn(array('data'=>$article_list,'status'=>$status));die;
		}

		 //加载变量
		 $this->assign(array(
			'article_list'=>$article_list
	     ));

		 $this->display('article_list');
	}

	//加载文章内容(文章内容修改)
	public function article_detail(){
		$aid = I('aid');
		$type = I('article_type',0,intval);

		if($type){
			$task_url =  U('Publishingtasks/index');		//回调地址
		}

		if(empty($aid)){
			header('Location:'.U('Home/Publishingtasks/index'));
		}
       
		//查询当前文章
		$detail  = D('Article')->article_detail($aid,1);
		$content = $detail['content'];
		$content = str_replace('href','data-href',$content);
		$detail['content'] = $content;

		//组装分享url
		$share_url = "http://".$_SERVER['HTTP_HOST'].U('Home/Publish/article_detail',array('aid'=>$aid));

		if(empty($detail)){
			header('Location:'.U('Home/Article/article_list'));
		}
		//查询插入模板
		$ad_list = D('Ad')->select_ad_list($this->uid);
		 //加载变量
		 $this->assign(array(
			'detail'=>$detail,
			'ad_list'=>$ad_list,
			'contents'=>htmlspecialchars_decode($detail['content']),
			'article_type'=>$detail['type'],//文章类型0站内，1获取
			'share_url'=>$share_url,
			'url'=>$task_url,
	     ));
		$this->display('article_edit');
	}

	//删除文章
	public function article_delete(){
		$aid = I('aid');
		if(empty($aid)){
			$this->ajaxReturn(array('status'=>'-1','msg'=>'文章删除失败'));
		}
		$judge = D('Article')->delete_detail($this->uid,$aid);

		if($judge){
			$this->ajaxReturn(array('status'=>'1','msg'=>'文章删除成功'));
		}else{
			$this->ajaxReturn(array('status'=>'-1','msg'=>'文章删除失败'));
		}
	}

	//站内文章(后台发布的文章)
	public function article_list_inside(){

		$page         = I('page',0,'intval');
		$limit        = '';
		$index        = 15;
		$page_all     = 0;
		$files        = 'id,title,createtime,taxis';
		$cat_id       = I('cat_id',0,'intval');
		//获取页数
		if(!empty($page)){
			$now_page = ($page + 1);
			$page_all = $page * $index;
			$limit    = $page_all.','.$index;
		}else{
			$limit    = '0,15';
		}
		
		//查询文章分类
		$article_cate  = M('ArticleCate')->where('parent_id = 0 and status = 1')->field('cat_name,id')->select();
		
		//文章列表
		$article_list = D('Article')->article_list_all($limit,$files,$cat_id);
		//ajax分页
		if(IS_AJAX){
			if(!empty($article_list)){
				foreach($article_list as $k=>$v){
					$article_list[$k]['createtime'] = date('Y年m月d日 H:i:s',$v['createtime']);
				}
				$status = 1;
			}else{
				$status = -1;
			}
			return $this->ajaxReturn(array('data'=>$article_list,'status'=>$status));
		}
		
		
		//加载变量
		$this->assign(array(
			'article_list'=>$article_list,
			'cat_id'=>$cat_id, //分类id用于分类模板显示
			'article_cate'=>$article_cate, //分类数据，用于分类模板显示
			'article_cate_url'=>U('Home/Article/article_list_inside')//用于分类url
	    ));
		$this->display('article_list_inside');
	}

	//站内文章编辑(后台发布的文章)
	public function article_detail_inside(){
		$aid = I('aid',0,'intval');
		if(empty($aid)){
			header('Location:'.U('Home/Article/article_list_inside'));
		}
		//查询当前文章(站内文章)
		$detail = D('Article')->article_detail_inside($aid,$this->bid);
		if(empty($detail)){
			header('Location:'.U('Home/Article/article_list_inside'));
		}
		//查询插入模板
		$ad_list = D('Ad')->select_ad_list($this->uid,$this->bid);
	 	//加载变量
		$this->assign(array(
			'detail'=>$detail,
			'contents'=>htmlspecialchars_decode($detail['content']),
			'article_type'=>0,//文章类型0站内，1获取
			'showtitle'=>1,//显示标题
			'ad_list'=>$ad_list
	    ));
		$this->display('article_edit');
	}

	//显示广告内容
	public function display_way(){
		$this->display('display_way');
	}

	//怎么用
	public function how_use(){
		$this->display('how_use');
	}

	//新建文章
	public function our_article(){
		//等级不够不能进去操作
		// $status = judge_member_probation($this->opt,$this->info);
		// if($this->info['level'] == '0' && !$status){
		// 	prompt();
		// 	die();
		// }
		
		$this->assign(array(
			'our_article'=>1
	    ));
		$this->display('article_edit');
	}

	//抓取展示页面
	public function display_article(){
		$url =  I('url');
		$url = base64_decode($url);
		if(strpos($url,'http') !== 0){
			$url = 'http://'.$url;
		};

		$this->assign(array(
			'url'=>$url,
	     ));
		$this->display('display_article');
	}
	
	//组装iframe视频链接
	public function display_iframe(){
		$url  = I('url');
		if(empty($url)){
			return false;
		}
	
		//QQ视频
		if(strpos($url,'v.qq.com') !== false){	
			
			$video_url = display_compose_iframe($url,'qq');
		
		//土豆视频
		}else if(strpos($url,'www.tudou.com') !== false){
			$video_url = display_compose_iframe($url,'tudou');
		
		//优酷视频
		}else if(strpos($url,'v.youku.com') !== false){
			
			$video_url = display_compose_iframe($url,'youku');
		}
	
		if(!empty($video_url)){
			$this->ajaxReturn(array('error'=>1,'url'=>$video_url));
		}else{
			$this->ajaxReturn(array('error'=>0,'url'=>$video_url));			
		}
	}
	

	
	//用于插入文章历史记录
	public function insert_article_log(){
		$url =  I('url','');
		//判断会员等级和使用天数
		$judge_member =  judge_member_probation($this->opt,$this->info);
		if($this->info['level'] == '0' && !$judge_member){
			$this->ajaxReturn(array('error'=>1,'msg'=>'非会员不能使用'));
	    }

		if(empty($url)){
			$this->ajaxReturn(array('error'=>1,'msg'=>'链接不能为空'));
		}

		$url = base64_decode($url);
		if(!preg_match('/(http:\/\/)|(https:\/\/)/i',$url)){
			$this->ajaxReturn(array('error'=>1,'msg'=>'请填写正确有效的链接'));
		}
		
		//搜索的url没有http前缀，没有最后斜杠
		$search_url = preg_replace('/(http:\/\/)|(https:\/\/)|\/.*|\?.*/i','',$url);
		$preg_match_info = M('ContentPregMatch')->where(array('url'=>$search_url))->field('preg_match,article_source,useragent')->find();

		if(empty($preg_match_info)){
			$this->ajaxReturn(array('error'=>1,'msg'=>'未支持此网站文章或网络请求失败'));
		}
		
		$result_log = M('ContentLog')->where('url = "'.$url.'"')->field('id,content,url')->find();
		$ac = $result_log['id'];

		//搜寻数据库是否有读取过链接，如果有直接读数据库，
		if(!empty($result_log)){
			$get_contest = htmlspecialchars_decode($result_log['content']);
		}else {
			$get_contest = file_put_article($url, $preg_match_info['preg_match'], $preg_match_info['useragent']);

			//组装插入数据的显示(插入ng_content_log,记录用户记录表)
			if (empty($get_contest)) {
				$this->ajax_data(0, '未支持此网站文章或网络请求失败');
			}

			$article_source = $preg_match_info['article_source'];

			$date = array(
				'uid'=>$this->uid,
				'content'=>htmlspecialchars($get_contest),
				'article_source'=>$article_source,
				'url'=>$url,
				'createtime'=>NOW_TIME,
	            'bid'=>$this->bid,
			);
			$ac = D('Article')->insert_content_log($date);
		}
		
		if($ac){
			$this->ajaxReturn(array('error'=>0,'msg'=>'获取文章成功','article_id'=>$ac));
		}else{
			$this->ajaxReturn(array('error'=>1,'msg'=>'未支持此网站文章或网络请求失败'));
		}
	}
	
}
